package timing.ukulele.log.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.syslog.view.LogVO;
import timing.ukulele.log.persistent.SysLog;
import timing.ukulele.log.service.SysLogService;

import java.util.ArrayList;

@RestController
@RequestMapping("/log")
public class SysLogController {

    private final SysLogService service;

    public SysLogController(SysLogService sysLogService) {
        this.service = sysLogService;
    }

    @GetMapping("{id}")
    public ResponseData<LogVO> getLogDetail(@PathVariable("id") Long id) {
        SysLog log = service.getById(id);
        LogVO vo = null;
        if (log != null) {
            vo = new LogVO();
            BeanUtils.copyProperties(log, vo);
        }
        return ResponseData.success(vo);
    }

    @GetMapping("page/{current}/{size}")
    public ResponseData<Page<LogVO>> getPage(@PathVariable("current") int current, @PathVariable("size") int size) {
        if (size == 0) {
            size = 10;
        }
        if (current == 0) {
            current = 1;
        }
        IPage<SysLog> page = service.getPage(new SysLog(), current, size);
        Page<LogVO> voPage = new Page<>();
        if (page != null && !CollectionUtils.isEmpty(page.getRecords())) {
            ArrayList<LogVO> voList = new ArrayList<>(page.getRecords().size());
            page.getRecords().forEach(po -> {
                LogVO vo = new LogVO();
                BeanUtils.copyProperties(po, vo);
                voList.add(vo);
            });
            voPage.setRecords(voList);
        }
        return ResponseData.success(voPage);
    }
}
